package com.srs.backend.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.backend.mapper.*;
import com.srs.backend.pojo.*;
import com.srs.backend.service.UserService;
import com.srs.backend.utils.IdentityAuthenticationUtil;
import com.srs.backend.utils.JwtUtil;
import com.srs.backend.utils.Result;
import com.srs.backend.utils.UserDetailsImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private ClientMapper clientMapper;
    @Resource
    private ServerMapper serverMapper;
    @Resource
    private ChefMapper chefMapper;
    @Resource
    private ManagerMapper managerMapper;

    @Resource
    private AuthenticationManager authenticationManager;
    @Override
    public Result getAll() {
        return Result.ok("success", userMapper.selectList(null));
    }

    @Override
    public Result login(Map<String, String> data) {
        String username = data.get("username");
        String password = data.get("password");
        String idKindString = data.get("id_kind");
        if (idKindString == null || idKindString.length() == 0) {
            return Result.error("用户身份缺失");
        }
        Integer idKind = null;
        try {
            idKind = Integer.parseInt(idKindString);
        } catch (NumberFormatException e) {
            return Result.error("用户身份非法");
        }
        if (username == null || password == null) {
            return Result.error("用户名或密码为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<User> userList = userMapper.selectList(queryWrapper);
        if (userList.isEmpty()) {
            return Result.error("用户不存在");
        }
        if (userList.get(0).getIdKind() != idKind) {
            return Result.error("用户身份非法");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        User user = loginUser.getUser();
        String jwt = JwtUtil.createJWT(user.getId().toString());
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);



        return Result.ok("success", map);
    }

    @Override
    public Result register(Map<String, String> data) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String username = data.get("username");
        String password = data.get("password");
        String confirmedPassword = data.get("confirmed_password");
        String baseInvitationCode = "1234";
        String idKindString = data.get("id_kind");
        String invitationCode = data.get("invitation_code");

        if (idKindString == null || idKindString.length() == 0) {
            return Result.error("用户身份缺失");
        }
        Integer idKind = null;
        try {
            idKind = Integer.parseInt(idKindString);
        } catch (NumberFormatException e) {
            return Result.error("用户身份非法");
        }

        if (idKind < 0 || idKind > 3) {
            return Result.error("用户身份非法");
        }

        if (idKind != 0 && !baseInvitationCode.equals(invitationCode)) {
            return Result.error("邀请码错误");
        }

        if (username == null || password == null || confirmedPassword == null) {
            return Result.error("用户名或密码为空");
        }
        if (username.length() < 5 || username.length() > 15) {
            return Result.error("用户名过短或过长");
        }
        username = username.trim();
        if (username.length() < 5 || username.length() > 15) {
            return Result.error("用户名过短或过长");
        }
        if (password.length() < 8 || password.length() > 20) {
            return Result.error("密码过短或过长");
        }
        if (!password.equals(confirmedPassword)) {
            return Result.error("两次输入的密码不一致");
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        if (!userMapper.selectList(userQueryWrapper).isEmpty()) {
            return Result.error("用户名已存在");
        }

        User curUser = new User(null, username, passwordEncoder.encode(password), idKind, null);

        userMapper.insert(curUser);
        // 创建user对应的userinfo
        // 这里还没写

        if (idKind == 0) {
            clientMapper.insert(new Client(null,"默认用户名",null,"11111111111",null,null, null, curUser.getId()));
        } else if (idKind == 1) {
            serverMapper.insert(new Server(null, "默认用户名", null, "11111111111", null, curUser.getId()));
        } else if (idKind == 2) {
            chefMapper.insert(new Chef(null, "默认用户名", null, "11111111111", null, curUser.getId()));
        } else if (idKind == 3) {
            managerMapper.insert(new Manager(null, "默认用户名", null, "11111111111", null, curUser.getId()));
        }

        return Result.ok("success");
    }

    @Override
    public Result addUser(Map<String, String> data) {
        // username: XXX ; password: XXX
        String username = data.get("username");
        String password = data.get("password");
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 逻辑判断
        password = passwordEncoder.encode(password);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        List<User> userList = userMapper.selectList(queryWrapper);

        if (!userList.isEmpty()) {
            return Result.error();
        }

        userMapper.insert(new User(null, username, password, null, null));

        String message = "abc";
        return Result.ok("success", message);
    }

    @Override
    public Result deleteUser(Map<String, String> data) {
        String id_str = data.get("id");
        Integer id = null;

        System.out.println(data);
        return  Result.ok();

//        try {
//            id = Integer.parseInt(id_str);
//
//        } catch (Exception e) {
//            return Result.error("ID非法");
//        }
//
//        // 逻辑判断
//
//        userMapper.deleteById(id);
//
//        return Result.ok("success");
    }

    @Override
    public Result updateUser(Map<String, String> data) {
        String id_str = data.get("id");
        String username = data.get("username");
        String password = data.get("password");
        Integer id = null;

        try {
            id = Integer.parseInt(id_str);
        } catch (Exception e) {
            return Result.error("id error");
        }

        if (username == null || username.length() < 3 || username.length() > 40) {
            return Result.error("用户名不合规范");
        }

        ///

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id" ,id);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            return Result.error("用户不存在");
        }

        userMapper.updateById(new User(id, username, password, null, null));

        return Result.ok("success");
    }

    @Override
    public Result getCurUserInfo() {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();

        User user = loginUser.getUser();
        user.setPassword("");
        return Result.ok(user);
    }
}
